//@ts-nocheck
import {createStore} from 'redux';
import rootReducer from './reducers';

//如何定一个专业的中间件 ---> 实现thunk异步中间件
//格式是定死的 柯里化 三层
const promise = function (middlewareAPI: any) {//api 你理解为接受的是store即可, 只是这个store的dispatch方法是我们中间最后返回的那个函数（给原生的dispatch包了一层(或则说n层,如果有多个中间件)）
  return function (next: any) {//调用下一个中间件的方法 现在你可以理解为store.dispatch
    return function (action: any) {//dispatch要派发的动作
      if (typeof action.then === 'function') { //说明是一个thunk 异步任务 交给它自己处理即可
        return action.then(newAction=>middlewareAPI.dispatch(newAction));
      }
      return next(action);//调用下一个中间件
    }
    //↑以后再调用store.dispatch调用就是这个函数, applyMiddleware里会换掉原本的dispatch(return {...store, dispatch})
  }
}

function applyMiddleware(middleware){
  return function(createStore){
    return function(reducer){
      const store = createStore(reducer);

      // const dispatch = middleware(store)(store.dispatch);

      // eslint-disable-next-line prefer-const
      let dispatch; //← 会被狸猫换太子 变成改造后的dispatch方法
      const middlewareAPI = {
        getState: store.getState,
        dispatch: (action) => dispatch/*← 这里这个dispatch是下面 dispatch = middleware(middlewareAPI)(store.dispatch) 赋的值*/(action)
      }

      dispatch = middleware(middlewareAPI)(store.dispatch);

      return {
        ...store,
        dispatch
      }
    }
  }
}

//const store = createStore(rootReducer);
const store = applyMiddleware(promise)(createStore)(rootReducer);

export default store;
